package com.qf.limit.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.limit.commons.exception.ServiceException;
import com.qf.limit.commons.r.Codes;
import com.qf.limit.commons.utils.UserUtils;
import com.qf.limit.dao.FriendrequestDao;
import com.qf.limit.entity.Friendrequest;
import com.qf.limit.entity.vo.FriendRequestVo;
import com.qf.limit.entity.vo.RequestHandlerVo;
import com.qf.limit.service.FriendrequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * (Friendrequest)表服务实现类
 *
 * @author makejava
 * @since 2024-09-13 12:48:11
 */
@Service("friendrequestService")
public class FriendrequestServiceImpl extends ServiceImpl<FriendrequestDao, Friendrequest> implements FriendrequestService {

    @Autowired
    private FriendrelationServiceImpl friendrelationService;

   @Override
    public boolean save(Friendrequest entity) {
       //设置申请人id
       entity.setFromId(UserUtils.getUid());
       //判断当前用户被申请者id是否已经是好友
       if (friendrelationService.isFriendRelation(entity.getFromId(),entity.getToId())){
           throw new ServiceException(Codes.IS_FIRENDS);

       }
       //判断当前用户被申请者id是否已经发送过好友申请
       Long count = this.query()
               .eq("from_id",entity.getFromId())
               .eq("to_id",entity.getToId())
               .ne("status",2)
               .count();
       if (count > 0){
           throw new ServiceException(Codes.IS_REQUEST);
       }
       return super.save(entity);
   }

    @Override
    public List<FriendRequestVo> queryMeRequest() {
        return getBaseMapper().queryMeRequest(UserUtils.getUid());
    }

    @Override
    public int requestHandler(RequestHandlerVo requestHandlerVo) {
       Friendrequest friendrequest = this.getById(requestHandlerVo.getId());
       if (friendrequest == null) {
           throw new ServiceException(Codes.DATA_ERROR);
       }
       this.update()
               .set("status",requestHandlerVo.getStatus())
               .set("update_time",new Date())
               .eq("id",requestHandlerVo.getId())
               .update();
       if (requestHandlerVo.getStatus()==1){
           friendrelationService.addFriendRelation(
                   friendrequest.getFromId(),
                   friendrequest.getToId(),
                   friendrequest.getBeizhu(),
                   requestHandlerVo.getBeizhu());

       }
        return 1;
    }
}

